<script setup lang="ts">
import {ElDropdown, ElDropdownMenu, ElDropdownItem, ElMessageBox, ElMessage} from 'element-plus'
import {useI18n} from '@/hooks/web/useI18n'
import {useCache} from '@/hooks/web/useCache'
import {resetRouter} from '@/router'
import {useRouter} from 'vue-router'
import {loginOutApi} from '@/api/login'
import {useDesign} from '@/hooks/web/useDesign'
import {useTagsViewStore} from '@/store/modules/tagsView'
import {useAppStore} from '@/store/modules/app'
import {getUsage} from '@/api/eq'
import {reactive, ref, toRefs} from "vue";
import warningSond from "@/assets/audio/alarm.mp3";
import {verifyPassword} from "@/api/user";
import {CircleCloseFilled, WarningFilled} from "@element-plus/icons-vue";

const appStore = useAppStore()

const tagsViewStore = useTagsViewStore()

const {getPrefixCls} = useDesign()

const prefixCls = getPrefixCls('user-info')

const {t} = useI18n()

const {wsCache} = useCache()

const {replace} = useRouter()

/** 异常患者提醒相关代码 开始 */
const dialogVisible = ref(false);
const isPlayAudio = ref(true);
const warningAudio = new Audio();
warningAudio.src = warningSond;
warningAudio.loop = true;
const openPopover = ref(false);

const names: any = ref([]);
const usedNames: any = ref([]);
const expNames: any = ref([]);
const invalidNames: any = ref([]);
const outOfAreaNames: any = ref([]);
const noWearDevice: any = ref([]);
const getNoUsageNames = () => {
  getUsage().then((res: any) => {
    let data = res.data;
    // 未正确佩戴设备的患者
    let noWearing = data?.noWearing || [];
    if (noWearing.length > 0) {
      noWearDevice.value = noWearing;
      openPopover.value = true;
      if(isPlayAudio.value) {
        // 播放
        warningAudio.play();
      }
    } else {
      noWearDevice.value = [];
      openPopover.value = false;
      warningAudio.pause();
    }

    dialogVisible.value = false;

    // 未使用体温传感器的患者
    let noTemperatureData = data?.noTemperatureData || [];
    if (noTemperatureData.length > 0) {
      let str = [];
      for (let i = 0; i < noTemperatureData.length; i++) {
        str.push(noTemperatureData[i].patientName);
      }
      dialogVisible.value = true;
      names.value = str;
    } else {
      names.value = [];
    }

    // 使用已被使用过的传感器的患者列表
    let sensorUsed = data?.sensorUsed || [];
    if (sensorUsed.length > 0) {
      let str = [];
      for (let i = 0; i < sensorUsed.length; i++) {
        str.push(sensorUsed[i].patientName);
      }
      dialogVisible.value = true;
      usedNames.value = str;
    } else {
      usedNames.value = [];
    }

    // 使用已失效的传感器的患者列表
    let sensorExp = data?.sensorExp || [];
    if (sensorExp.length > 0) {
      let str = [];
      for (let i = 0; i < sensorExp.length; i++) {
        str.push(sensorExp[i].patientName);
      }
      dialogVisible.value = true;
      expNames.value = str;
    } else {
      expNames.value = [];
    }

    // 使用不合法的传感器的患者列表
    let sensorInvalid = data?.sensorInvalid || [];
    if (sensorInvalid.length > 0) {
      let str = [];
      for (let i = 0; i < sensorInvalid.length; i++) {
        str.push(sensorInvalid[i].patientName);
      }
      dialogVisible.value = true;
      invalidNames.value = str;
    } else {
      invalidNames.value = [];
    }

    // 超出使用范围的传感器的患者列表
    let sensorOutOfArea = data?.sensorOutOfArea || [];
    if (sensorOutOfArea.length > 0) {
      let str = [];
      for (let i = 0; i < sensorOutOfArea.length; i++) {
        str.push(sensorOutOfArea[i].patientName);
      }
      dialogVisible.value = true;
      outOfAreaNames.value = str;
    } else {
      outOfAreaNames.value = [];
    }
  });
}
getNoUsageNames();
// 设置一个每两分钟执行一次的定时器
setInterval(function () {
  getNoUsageNames();
}, 120 * 1000);

const stopPlayAideo = () => {
  isPlayAudio.value = ! isPlayAudio.value;
  if(isPlayAudio.value && noWearDevice.value.length > 0) {
    // 播放
    warningAudio.play();
  } else {
    warningAudio.pause();
  }
}
//表格配置
const tableColumn = [
  {prop: 'visitNo', label: '序列号', align: 'center'},
  {prop: 'patientName', label: '姓名', width: 100, align: 'center'},
  {prop: 'bedNo', label: '床位号', width: 80, align: 'center'},
] as Table.Column[];
interface State {
  option: Table.Option
}
const state = reactive<State>({
  option: {
    loading: false,
    showPagination: false,
    height: 300,
  }
});
const {option} = toRefs(state);
/** 异常患者提醒相关代码  结束 */

const loginOut = () => {
  ElMessageBox.confirm(t('common.loginOutMessage'), t('common.reminder'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      const res = await loginOutApi().catch(() => {
      })
      if (res) {
        wsCache.clear()
        tagsViewStore.delAllViews()
        resetRouter() // 重置静态路由表
        replace('/login')
      }
    })
    .catch(() => {
    })
}

/** 提醒修改密码 */
const reqValidPwd = () => {
  verifyPassword().then((res: any) => {
    let data = res.data;
    if(!data) {
      ElMessage({
        type: 'warning',
        duration: 0,
        showClose: true,
        placement: 'top-right',
        message: '您好！为了账号安全，请在个人中心修改初始密码！',
      })
    }
  });
}
reqValidPwd();
</script>

<template>
  <div style="margin: 0 10px; cursor: pointer;">
    <el-popover placement="left" :width="450" :visible="openPopover">
      <template #reference>
        <img v-if="noWearDevice.length > 0 && isPlayAudio " @click="stopPlayAideo" @mouseover="openPopover=true" alt="" src="@/assets/imgs/alarm.png" class="w-[calc(var(--tags-view-height))] rounded-[50%] animating-img" />
        <img v-if="noWearDevice.length > 0 && !isPlayAudio " @click="stopPlayAideo" @mouseover="openPopover=true" alt="" src="@/assets/imgs/alarm_close.png" class="w-[calc(var(--tags-view-height))] rounded-[50%]" />
        <img v-if="noWearDevice.length <= 0 && isPlayAudio " @click="stopPlayAideo" @mouseover="openPopover=true" alt="" src="@/assets/imgs/alarm_grey.png" class="w-[calc(var(--tags-view-height))] rounded-[50%]" />
        <img v-if="noWearDevice.length <= 0 && !isPlayAudio " @click="stopPlayAideo" @mouseover="openPopover=true" alt="" src="@/assets/imgs/alarm_grey_close.png" class="w-[calc(var(--tags-view-height))] rounded-[50%]" />
      </template>

      <el-alert title="以下患者未正确佩戴设备！" type="error" :closable="false" show-icon style="margin-bottom: 10px;" />
      <Table :column="tableColumn" :table-data="noWearDevice" :option="option"></Table>
      <div style="margin-top: 10px; text-align: right;">
        <el-button @click="openPopover = false">关 闭</el-button>
      </div>
    </el-popover>
  </div>
  <ElDropdown :class="prefixCls" trigger="click">
    <div class="flex items-center mr-2" style="cursor: pointer; color: #fff;">
      <img
        src="@/assets/imgs/avatar.jpg"
        alt=""
        class="w-[calc(var(--tags-view-height))] rounded-[50%]"
      />
      <span class="<lg:hidden text-14px pl-[5px] text-[var(--top-header-text-color)] mr-4">{{
        wsCache.get(appStore.getUserInfo).fullName
      }}</span>
    </div>
    <template #dropdown>
      <ElDropdownMenu>
        <ElDropdownItem divided>
          <div @click="loginOut">{{ t('common.loginOut') }}</div>
        </ElDropdownItem>
      </ElDropdownMenu>
    </template>
  </ElDropdown>

  <el-dialog v-model="dialogVisible" title="提示" width="30%" modal-class="my_modal" append-to-body z-index="999999"
             :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">

    <div v-if="names.length > 0" style="line-height: 30px;">
      <el-text type="warning">
        <el-icon><WarningFilled /></el-icon>
        患者<b v-for="(val, index) in names">{{val + (index == names.length-1 ? "" : "、")}}</b>未正确使用体温传感器！
      </el-text>
    </div>
    <div v-if="usedNames.length > 0" style="line-height: 30px;">
      <el-text type="danger">
        <el-icon><CircleCloseFilled /></el-icon>
        患者<b v-for="(val, index) in usedNames">{{val + (index == usedNames.length-1 ? "" : "、")}}</b>使用的体温传感器已被其他患者使用！
      </el-text>
    </div>
    <div v-if="expNames.length > 0" style="line-height: 30px;">
      <el-text type="danger">
        <el-icon><CircleCloseFilled /></el-icon>
        患者<b v-for="(val, index) in expNames">{{val + (index == expNames.length-1 ? "" : "、")}}</b>使用的体温传感器已失效！
      </el-text>
    </div>
    <div v-if="invalidNames.length > 0" style="line-height: 30px;">
      <el-text type="danger">
        <el-icon><CircleCloseFilled /></el-icon>
        患者<b v-for="(val, index) in invalidNames">{{val + (index == invalidNames.length-1 ? "" : "、")}}</b>使用的体温传感器无效或不合法！
      </el-text>
    </div>
    <div v-if="outOfAreaNames.length > 0" style="line-height: 30px;">
      <el-text type="danger">
        <el-icon><CircleCloseFilled /></el-icon>
        患者<b v-for="(val, index) in outOfAreaNames">{{val + (index == outOfAreaNames.length-1 ? "" : "、")}}</b>体温传感器不在可使用的地区范围！
      </el-text>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false"> 确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style>
.my_modal {
  background-color: rgba(0, 0, 0, 0.9);
}

.animating-img {
  animation: zoomAnimation 2s infinite alternate;
}

@keyframes zoomAnimation {
  0% {
    transform: scale(1); /* 开始时元素正常大小 */
  }
  50% {
    transform: scale(1.2); /* 中间放大到1.5倍 */
  }
  100% {
    transform: scale(1); /* 结束时元素回到正常大小 */
  }
}
</style>
